import React, { useState, useEffect } from 'react';
import { Table, Button, notification, Modal, Form, Space, Select, Input, Tag, Alert, message } from 'antd';
import { useAuditList, useAuditNews } from '../../../hooks/useNewsManage';
import { News, AuditState } from '../../../types';
import { useNavigate, useLocation } from 'react-router-dom';
import useSimpleAuth from '../../../hooks/useSimpleAuth';
import { useQueryClient } from '@tanstack/react-query';
import './Audit.scss';

const { Option } = Select;
const { TextArea } = Input;

const Audit: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [currentNews, setCurrentNews] = useState<News | null>(null);
  const queryClient = useQueryClient();
  
  // 获取URL参数，检查是否需要刷新
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const shouldRefresh = searchParams.get('refresh') === 'true';
  
  // 获取待审核新闻列表
  const { data: newsList = [], isLoading, refetch } = useAuditList();
  
  // 如果URL中有refresh参数，强制刷新数据
  useEffect(() => {
    if (shouldRefresh) {
      console.log('检测到refresh参数，强制刷新审核列表数据');
      // 先清除缓存
      queryClient.invalidateQueries({ queryKey: ['news', 'audit'] });
      // 然后重新获取数据
      refetch();
      
      // 清除URL中的参数，防止再次刷新时重复刷新
      navigate('/audit-manage/audit', { replace: true });
    }
  }, [shouldRefresh, refetch, queryClient, navigate]);
  
  // 使用简化版权限钩子
  const { isSuperAdmin, isRegionAdmin, filterNewsByDepartment, getUserRegion } = useSimpleAuth();
  
  // 使用钩子获取用户信息
  const userRegion = getUserRegion();
  
  // 审核操作
  const auditNewsMutation = useAuditNews();
  
  // 过滤出具有审核权限区域的新闻，使用增强的部门隔离逻辑
  const getAuditList = () => {
    try {
      // 确保 newsList 是数组
      const newsArray = Array.isArray(newsList) ? newsList : [];
      
      // 使用钩子中的方法，现在已经正确包装了auth方法
      return filterNewsByDepartment(newsArray);
    } catch (error) {
      console.error('过滤新闻列表失败:', error);
      return [];
    }
  };
  
  // 显示审核模态框
  const handleAudit = (item: News) => {
    setCurrentNews(item);
    setVisible(true);
    form.resetFields();
  };
  
  // 查看新闻详情
  const handleView = (id: number | string) => {
    navigate(`/news-manage/preview/${id}`);
  };
  
  // 提交审核
  const handleSubmit = () => {
    form.validateFields().then(values => {
      if (!currentNews) return;
      
      const { auditState, reason } = values;
      const newsId = currentNews._id || currentNews.id || currentNews.seqId || '';
      
      // 详细记录审核参数
      console.log('提交审核:', {
        newsId,
        auditState: Number(auditState),
        reason,
        // 枚举值对照
        APPROVED: AuditState.APPROVED, // 2
        REJECTED: AuditState.REJECTED, // 3
        // 用于调试
        isApproved: Number(auditState) === AuditState.APPROVED,
        isRejected: Number(auditState) === AuditState.REJECTED
      });
      
      auditNewsMutation.mutate({
        id: newsId,
        auditState: Number(auditState),
        reason: reason
      }, {
        onSuccess: (response) => {
          setVisible(false);
          
          // 记录审核成功的响应
          console.log('审核成功，响应:', response);
          
          // 根据审核结果显示不同消息
          if (Number(auditState) === AuditState.APPROVED) {
            notification.success({
              message: '审核通过',
              description: `《${currentNews.title}》已审核通过，等待发布`,
              placement: 'bottomRight'
            });
          } else {
            notification.warning({
              message: '审核拒绝',
              description: `《${currentNews.title}》被拒绝: ${reason || '无原因'}`,
              placement: 'bottomRight'
            });
          }
          
          // 审核完成后导航到审核列表页面，传递审核状态信息
          setTimeout(() => {
            navigate(`/audit-manage/list?auditState=${auditState}&t=${Date.now()}`);
          }, 1000);
        },
        onError: (error) => {
          console.error('审核失败:', error);
          // 显示错误消息
          message.error('审核操作失败，请重试');
        }
      });
    });
  };
  
  // 获取过滤后的数据列表
  const filteredNewsList = getAuditList();
  
  // 定义表格列
  const columns = [
    {
      title: 'ID',
      dataIndex: 'seqId',
      width: 80
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      width: 300,
      ellipsis: true,
      render: (title: string, item: News) => {
        const id = item._id || item.id || item.seqId || '';
        return <a onClick={() => handleView(id)}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 100
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      width: 120,
      render: (category: { title: string } | undefined) => category?.title || '未分类'
    },
    {
      title: '区域',
      dataIndex: 'region',
      width: 100,
      render: (region: string) => (
        <Tag color={region === userRegion ? 'blue' : 'default'}>
          {region || '全球'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      render: (time: number) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      width: 120,
      render: (_: unknown, item: News) => (
        <Space>
          <Button 
            type="primary" 
            onClick={() => handleAudit(item)}
          >
            审核
          </Button>
        </Space>
      )
    }
  ];
  
  // 显示权限提示信息
  const renderPermissionAlert = () => {
    if (isSuperAdmin()) {
      return (
        <Alert
          message="您是超级管理员，可以查看和审核所有部门的新闻"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
      );
    }
    
    if (isRegionAdmin()) {
      return (
        <Alert
          message={`您是管理员，只能查看和审核${userRegion || ''}部门的新闻`}
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      );
    }
    
    return (
      <Alert
        message="您没有审核权限，无法查看待审核新闻"
        type="error"
        showIcon
        style={{ marginBottom: 16 }}
      />
    );
  };
  
  return (
    <div className="audit-news">
      <h2>新闻审核</h2>
      
      {renderPermissionAlert()}
      
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end' }}>
        <Button onClick={() => refetch()} type="primary">
          刷新数据
        </Button>
      </div>
      
      <Table 
        dataSource={filteredNewsList} 
        columns={columns}
        pagination={{ 
          pageSize: 5,
          showTotal: (total) => `共 ${total} 条` 
        }}
        rowKey={record => String(record.seqId || record._id || record.id || '')}
        loading={isLoading}
        locale={{ emptyText: '暂无待审核新闻' }}
      />
      
      <Modal
        open={visible}
        title="审核新闻"
        okText="提交"
        cancelText="取消"
        onCancel={() => setVisible(false)}
        onOk={handleSubmit}
        destroyOnClose
      >
        <Form form={form} layout="vertical" preserve={false}>
          <Form.Item
            name="auditState"
            label="审核结果"
            rules={[{ required: true, message: '请选择审核结果' }]}
          >
            <Select placeholder="请选择审核结果">
              <Option value={AuditState.APPROVED}>通过</Option>
              <Option value={AuditState.REJECTED}>驳回</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => 
              prevValues.auditState !== currentValues.auditState
            }
          >
            {({ getFieldValue }) => (
              getFieldValue('auditState') === AuditState.REJECTED ? (
                <Form.Item
                  name="reason"
                  label="驳回原因"
                  rules={[{ required: true, message: '请填写驳回原因' }]}
                >
                  <TextArea rows={4} placeholder="请填写驳回原因" />
                </Form.Item>
              ) : null
            )}
          </Form.Item>
          
          {currentNews && (
            <div className="news-info">
              <h3>新闻信息</h3>
              <p><strong>标题:</strong> {currentNews.title}</p>
              <p><strong>作者:</strong> {currentNews.author}</p>
              <p><strong>区域:</strong> {currentNews.region || '全球'}</p>
              <p><strong>分类:</strong> {currentNews.category?.title || '未分类'}</p>
            </div>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default Audit; 